<template>
	<view class="">
		<view class="main-content" v-if="applyStatus == 2">
			<scroll-view scroll-y :style="{height: scrollHeight}" class="list-box form-data">
				<!-- <text class="title">zi</text> -->
				<uni-forms ref="masterEnterForm" :modelValue="FormData" :rules="rules" :border="false">
					<uni-forms-item label="姓名" name="name" required>
						<input type="text" placeholder="请输入姓名" v-model="FormData.name" style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="手机号" name="phone" required>
						<input type="number" placeholder="请输入手机号" v-model="FormData.phone" style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="性别" name="sex">
						<picker mode="selector" :value="sexIndex" @change="bindPickerChange" :range="array"
							range-key="name">
							<view class="row-end-1">
								<view style="text-align: right;">
									<text class="time_value" v-if="sexIndex >= 0">{{array[sexIndex].name}}</text>
									<text class="time_value" v-else style="opacity: 0.6;">请选择性别</text>
								</view>
								<uni-icons type="right" color="#666" size="36rpx"></uni-icons>
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="职位" name="positionType">
						<view style="text-align: right;">{{forrmatterEnmu(positionList,FormData.positionType)}}</view>
					</uni-forms-item>
					<uni-forms-item label="地址" name="province">
						<view class="row-end-1" @click="show = true">
							<view style="text-align: right;">
								<text class="placeholder-class" v-if="!region" style="opacity: 0.6;">请选择城市</text>
								<text v-else style="font-size: 28rpx;">{{region}}</text>
							</view>
							<uni-icons type="right" color="#666" size="36rpx"></uni-icons>
						</view>
					</uni-forms-item>
					<uni-forms-item label="详细地址" name="addr">
						<input type="text" placeholder="请输入详细地址" v-model="FormData.addr" style="text-align: right;" />
					</uni-forms-item>
					<!-- <uni-forms-item label=" " name="11" style="height: 0;">
					</uni-forms-item> -->
				</uni-forms>
				<!-- <view class="form-item-vertical">
					<view class="label">
						身份证反面照片
					</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.idCardFront" @afterRead="afterRead" @delete="deletePic"
							name="idCardFront" multiple :maxCount="1" :previewFullImage="true" width="198rpx"
							height="198rpx">
							<view class="upload-after">
								<u-icon name="plus" size="60rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
				<view class="form-item-vertical">
					<view class="label">身份证反面照片</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.idCardBack" @afterRead="afterRead" @delete="deletePic"
							name="idCardBack" multiple :maxCount="1" :previewFullImage="true" width="198rpx"
							height="198rpx">
							<view class="upload-after">
								<u-icon name="plus" size="60rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view> -->
				<view class="form-item-vertical">
					<view class="label">技能证书照片</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.idCardBack" @afterRead="afterRead" @delete="deletePic"
							name="idCardBack" multiple :previewFullImage="true" width="150rpx" height="150rpx"
							:maxCount="1">
							<view class="upload-after">
								<u-icon name="man-add-fill" size="100rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
			</scroll-view>
			<you-bottom-btn :btnConfig="bottomBtnConfig" @formSubmit="formSubmit" @testReport="testReport">
			</you-bottom-btn>
		</view>
		<apply-for image="../../../static/images/home/engineer.jpg" :title="'申请类型'" :placeholder="'请选择申请类型'"
			:type="'select'" @applySuccess="applySuccess" v-else-if="applyStatus == 0 || applyStatus == 3"></apply-for>

		<!-- 选择城市 -->
		<u-picker :show="show" ref="uPicker" :columns="cityColumns" @confirm="cityConfirm" keyName="cname"
			@change="changeHandler" @cancel="show = false"></u-picker>
	</view>
</template>

<script>
	import {
		baseUrl,
		baseImgUrl
	} from '@/config'
	import {
		getToken
	} from "@/utils/auth"
	import Home from '@/api/home'
	import Apply from '@/api/apply.js'
	import ApplyFor from './component/ApplyFor.vue'
	import {
		forrmatterEnmu
	} from '@/utils/index.js'
	export default {
		data() {
			return {
				FormData: {
					Tname: '',
					id: '',
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					id: {
						rules: [{
								required: true,
								errorMessage: '请输入身份证',
							},
							{
								minLength: 18,
								maxLength: 18,
								errorMessage: '身份证长度在18位',
							}
						]
					},
				},
				scrollHeight: '',
				bottomBtnConfig: [{
					text: '提交申请',
					class: 'confirm',
					funcName: 'formSubmit'
				}],
				fileImage: {
					idCardFront: [],
					idCardBack: [],
				},
				isApply: false,
				applyStatus: null,
				array: [{
						id: 1,
						name: '男'
					},
					{
						id: 2,
						name: '女'
					}
				],
				sexIndex: -1,
				positionList: [],
				show: false,
				cityColumns: [],
				cityList: [],
				region: '',
			}
		},
		components: {
			ApplyFor
		},
		onLoad() {
			setTimeout(() => {
				this.getApplyStatus()
			}, 0)
			this.scrollHeight = this.$store.getters.heightData.noTabMainHeight - 74 + 'px'
			this.getRoleType()
			this.getCityList()
		},
		onHide() {
			console.log(1111);
			this.fileImage= {
				idCardFront: [],
				idCardBack: [],
			}
		},
		onLaunch() {
			console.log(22222);
			this.fileImage= {
				idCardFront: [],
				idCardBack: [],
			}
		},
		methods: {
			forrmatterEnmu,
			// 当前账号申请状态
			async getApplyStatus() {
				let res
				res = await Apply.engineerStatus()
				if (res.code == 200) {
					// 0未申请 1审核中 2通过 3未通过
					console.log(11111111, this.applyStatus);
					if (res.data) {
						this.applyStatus = res.data.auditType
						console.log(22222, this.applyStatus);
						if (res.data.auditType == 2) {
							uni.setNavigationBarTitle({
								title: '资料补充'
							})
						} else if (res.data.auditType == 1) {
							uni.redirectTo({
								url: `/subPages/home/master/notExamine?title=工程师入驻&msg=请您耐心等待`
							})
						}
						this.FormData = res.data
						let city = res.data.citystring ? `/${res.data.citystring}` : ''
						let county = res.data.countystring ? `/${res.data.countystring}` : ''
						this.region = (res.data.provinceString || '') + city + county
						let index = this.array.findIndex(item => item.id == res.data.sex)
						if (index !== -1) {
							this.sexIndex = index
						}
						// 职位赋值
						// this.positionList.forEach(item => {
						// 	if (item.id == res.data.positionType) {
						// 		this.FormData.userPostion = item.name
						// 	}
						// })
						// 图片赋值
						if (res.data.skillCertificate) {
							this.fileImage.idCardBack.push({
								status: 'success',
								message: '',
								url: baseUrl + res.data.skillCertificate
							})
						}
					} else {
						this.applyStatus = 0
					}
				}
			},
			bindPickerChange(v) {
				this.sexIndex = v.detail.value
				if (v.detail.value == 0) {
					this.FormData.sex = 1
				} else {
					this.FormData.sex = 2
				}
			},
			// 工程师申请类型
			getRoleType() {
				Apply.roleType().then(res => {
					if (res.code == 200) {
						this.positionList = []
						res.data.forEach(item => {
							this.positionList.push({
								value: item.dictValue,
								label: item.dictLabel,
							})
						})
					}
				})
			},
			// 获取城市列表
			getCityList() {
				Home.getCity().then(res => {
					this.cityList = res.data
					this.cityColumns[0] = res.data?.filter(item => item.ctype == 1)
					this.cityColumns[1] = res.data?.filter(item => item.parentId == 2)
					this.cityColumns[2] = res.data?.filter(item => item.parentId == 52)
				})
			},
			formSubmit() {
				this.FormData.skillCertificate = this.getImageValue(this.fileImage.idCardBack[0]?.url)
				this.$refs.masterEnterForm.validate().then(res => {
					Apply.engineerChange(this.FormData).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '信息修改成功'
							})
							setTimeout(()=>{
								uni.navigateBack()
							},1000)
						}
					})
				}).catch(err => {})
			},
			getImageValue(url){
				if(url){
					if(url.indexOf('prod-api')!=-1){
						console.log(url.split('prod-api'));
						return url.split('prod-api')[1]
					}else{
						return url
					}
				}else{
					return null
				}
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.getRoleType()
				this.getApplyStatus()
			},
			uploadSelectStoreId() {

			},
			deletes() {

			},
			// 新增图片
			async afterRead(event) {
				console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileImage[`${event.name}`].length
				lists.map((item) => {
					this.fileImage[`${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				uni.uploadFile({
					url: baseUrl + '/common/upload',
					filePath: event.file[0].url,
					name: 'file',
					header: {
						"Authorization": 'Bearer ' + getToken()
					},
					// 成功函数
					success: (res) => {
						let item = this.fileImage[`${event.name}`][fileListLen]
						this.fileImage[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: JSON.parse(res.data).fileName
						}))
					},
					// 失败提示用户重新上传
					fail: error => {
						console.log('失败', error)
					}
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + getToken()
						},
						formData: {},
						success: (res) => {
							console.log(res)
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			deletePic(v) {
				this.fileImage.idCardBack.splice(v.index, 1)
			},
			// 查看是否申请成功
			applySuccess(v) {
				this.applyStatus = v.auditType
				this.FormData = v
			},
			// 城市改变事件
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					let parent = this.cityList.filter(item => item.parentId == value[0].id)
					picker.setColumnValues(1, this.cityList.filter(item => item.parentId == value[0].id))
					picker.setColumnValues(2, this.cityList.filter(item => item.parentId == parent[0].id))
				}
				if (columnIndex === 1) {
					picker.setColumnValues(2, this.cityList.filter(item => item.parentId == value[1].id))
				}
			},
			// 选择城市回调参数为包含columnIndex、value、values
			cityConfirm({
				value
			}) {
				let nameList = []
				value.forEach(item => {
					nameList.push(item.cname)
				})
				this.region = nameList.join('/')
				this.FormData.province = value[0].id
				this.FormData.provinceString = value[0].cname
				this.FormData.city = value[1].id
				this.FormData.cityString = value[1].cname
				this.FormData.county = value[2].id
				this.FormData.countyString = value[2].cname
				this.show = false
			},
		}
	}
</script>

<style scoped lang="less">
	.engineer {
		width: 100%;
		height: 100%;
	}

	.main-content {
		width: 100%;
		height: 100%;
		padding: 20rpx 30rpx;

		.list-box {
			padding: 20rpx 20rpx;
			border-radius: 16rpx;
			background: #ffffff;

			.title {
				padding: 20rpx 0;
				margin-left: 15rpx;
				display: block;
				border-bottom: 2rpx solid #acacac;
				font-family: "PingFang SC";
				font-size: 28rpx;
				font-style: normal;
				font-weight: 600;
				line-height: 40rpx;
				opacity: 0.9;
			}
		}
	}

	.form-item-vertical {
		margin-left: 15rpx;

		.label {
			color: #1a1a1a;
			font-size: 24rpx;
			padding: 20rpx 0;
			// &::before {
			// 	content: "*";
			// 	color: red;
			// 	font-size: 30rpx;
			// 	display: inline-block;
			// 	margin-right: 10rpx;
			// 	width: 5rpx;
			// 	height: 20rpx;
			// }
		}
	}

	.upload-box {
		height: 150rpx;
		width: 150rpx;
	}

	.upload-after {
		background: #F6F8FA;
		width: 150rpx;
		height: 150rpx;
		line-height: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/deep/ .u-upload__wrap {
		display: flex;
		flex-wrap: nowrap !important;
	}
</style>